<?php
/**
 登录检测并设置超全局cookie防止直接http无权限访问
 */
$adminEmail = $_POST['admin_email'];
if (empty($adminEmail)){
    echo "参数错误";
    echo "<br/>"."<a href='javascript:history.go(-1)'>返回</a>";
    exit();
}
$adminPassword = $_POST['admin_password'];

//连接数据库
$dsn = "mysql:host=127.0.0.1;dbname=blog";
$db = new pdo($dsn,"root","123456");

//更改默认的utf8为utf8mb4以防中文乱码
$db->exec("set names utf8mb4");

$selectSql = "select * from admin where admin_email='{$adminEmail}'";
$statement = $db ->query($selectSql);
$adminInfo = $statement ->fetch(PDO::FETCH_ASSOC);

//cookie+session

$rememberMe = $_POST['remember_me'] ?? '';

if ($adminInfo && $adminInfo['admin_password'] == $adminPassword){
    setcookie("admin_id", $adminInfo['admin_id']);
    setcookie("admin_email", $adminInfo['admin_email']);
    session_start();
    $_SESSION['admin_email'] = $adminEmail;
    $_SESSION['admin_name'] = $adminInfo['admin_name'];
    if ($rememberMe) {
        setcookie('PHP_SESSION_ID', session_id(), time() + 20);
    }
    echo "登录成功<br />";
    echo "<a href='category_list.php'>进入分类列表页面</a>"."<br/>";
    echo "<a href='article_list.php'>进入文章列表页面</a>"."<br/>";
    echo "<a href='admin_list.php'>进入管理员列表页面</a>";
    exit();
} else{
    echo "登录失败,账号或者密码错误"."<br/>"."<a href='javascript:history.go(-1)'>返回</a>";
}

//下面是cookie

if ($adminInfo && $adminInfo['admin_password'] == $adminPassword){
    setcookie("admin_id", $adminInfo['admin_id']);
    setcookie("admin_email", $adminInfo['admin_email']);
    echo "登录成功<br />";
    echo "<a href='category_list.php'>进入分类列表页面</a>"."<br/>";
    echo "<a href='article_list.php'>进入文章列表页面</a>"."<br/>";
    echo "<a href='admin_list.php'>进入管理员列表页面</a>";
    exit();
} else{
    echo "登录失败,账号或者密码错误"."<br/>"."<a href='javascript:history.go(-1)'>返回</a>";
}

//下面是session

$rememberMe = $_POST['remember_me'] ?? '';

if (!$admin) {
    echo "账户或者密码不匹配。<a href='login.php'>返回登录页</a>";
    exit();
}

if ($admin['admin_password'] == $adminPassword) {
    session_start();
    $_SESSION['admin_email'] = $adminEmail;
    $_SESSION['admin_name'] = $admin['admin_name'];
    if ($rememberMe) {
        setcookie('PHP_SESSION_ID', session_id(), time() + 20);
    }
    echo "登录成功。<a href='article_list.php'>前往文章列表页</a>";
    exit();
} else {
    echo "账户或者密码不匹配。<a href='login.php'>返回登录页</a>";
    exit();
}